package bookstudytest.socket;

import java.io.IOException;
import java.net.*;

/**
 * @Auther: Lee
 * @Date: 2018/6/21 17:35
 * @Description:
 */
public class SocketClientUDPDemo {
    public static void main(String[] args) {
        try {
            InetAddress inetAddress = InetAddress.getByName("localhost");
            int port = 9554;
            byte[] bytes = "我是客户端你好".getBytes();
            //封装数据包
            DatagramPacket datagramPacket = new DatagramPacket(bytes,bytes.length,inetAddress,port);
            //创建socket对象
            DatagramSocket datagramSocket = new DatagramSocket();
            //发送数据
            datagramSocket.send(datagramPacket);

            //接收服务器响应的数据
            byte[] a = new byte[1024];
            DatagramPacket packet = new DatagramPacket(a,a.length);
            datagramSocket.receive(packet);
            String response = new String(a, 0,packet.getLength());
            System.out.println(response);
            datagramSocket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
